package org.lzfto.flink.demo.utils;

import org.apache.flink.table.api.TableResult;
import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;

import java.util.*;

public class FlinkUtil {

    /**
     * 最大的打印记录
     */
    static final int MAX_PRINT_QTY=100;

    public static List<Map<String,Object>> printTable(TableResult sinkResult) {
        List<Map<String,Object>> rows=new LinkedList<>();
        List<String> colNames=sinkResult.getResolvedSchema().getColumnNames();
        Integer qty=0;
        CloseableIterator<Row> it=sinkResult.collect();
        while (it.hasNext()) {
            //遍历row的每个字段，并打印出来
            Row row=it.next();
            int colQty=row.getArity();
            Map<String,Object> rowData=new HashMap<>();
            for(int i=0;i<colQty;i++){
                Object colData=row.getField(i);
                String data="";
                if (colData!=null) {
                    data=colData.toString();
                }
                rowData.put(colNames.get(i), data);
            }
            rows.add(rowData);
            qty++;
            if (qty>=MAX_PRINT_QTY) {
                break;
            }
        }
        return rows;
    }
}
